/**
 * 泛娱区块链 - BindingPhone
 * http://menger.me
 * @author: zaric
 * @creation time: 2018-12-11
 */


'use strict';
import React from 'react';
import {Keyboard, ScrollView, ScrollViewComponent, StyleSheet, Text, TouchableOpacity, View} from 'react-native';
import NavigationBar from '../../component/navigation/NavigationBar';
import Container from '../../component/common/Container';
import HTMLView from '../../component/common/HTMLView';
import Images from '../../asset';
import ServicesApi from '../../config/ServicesApi';
import {diffTime} from '../../util/Tool'
import CommentView from '../../component/common/CommentView';
import ImageView from '../../component/common/ImageView';
import {inject, observer} from "mobx-react";

@inject('taskStore', 'loginStore')
@observer
class ArticleDetails extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            dataSource: {},
            showRightButton: false,
            focus: false,
        }
    }

    componentDidMount() {
        this.keyboardWillShowSub = Keyboard.addListener('keyboardWillShow', this.keyboardWillShow);
        this.keyboardWillHideSub = Keyboard.addListener('keyboardWillHide', this.keyboardWillHide);
        this.requestDataSources();
    }

    componentWillUnmount() {
        this.keyboardWillShowSub.remove();
        this.keyboardWillHideSub.remove();
    }

    //键盘显示
    keyboardWillShow = (event) => {
        this.setState({showRightButton: true})
    }
    //键盘隐藏
    keyboardWillHide = (event) => {
        this.setState({showRightButton: false})
    }

    requestDataSources = async () => {
        const {params} = this.props.navigation.state;
        let information_id = params.information_id;
        // console.log('传过来的information_id------------->', information_id);
        // information_id = 119529;
        let url = ServicesApi.INFORMATION_DETAIL;
        let data = {
            information_id,
            focus_user: global.secretKey
        };
        const result = await Services.post(url, data);
        // console.log('咨询详情返回------------>', result);
        if (result.code === StatusCode.SUCCESS_CODE) {
            this.setState({dataSource: result.data, focus: result.data.focus_state !== '0'});
            this._readTimes();
        }
    };

    //关注focus/save
    _onPressFollow = async () => {
        const {loginStore} = this.props;
        const {dataSource} = this.state;
        let url = ServicesApi.FOCUS_SAVE;
        let data = {
            focus_user: global.secretKey,
            focus_by_user: dataSource.author_id,
        };
        const result = await Services.post(url, data);
        if (result.code === StatusCode.SUCCESS_CODE) {
            this.requestDataSources();
            this.setState({focus: true});
            await loginStore.getUserData(global.secretKey);
        } else {
            ToastManager.show(result.dec || 'error')
        }
    };
    //取消关注
    _onCancelFollow = async () => {
        const {loginStore} = this.props;
        const {dataSource} = this.state;
        let url = ServicesApi.FOCUS_DEL;
        let data = {
            focus_user: global.secretKey,
            focus_by_user: dataSource.author_id,
            type: 'field',
        };
        const result = await Services.post(url, data);
        if (result.code === StatusCode.SUCCESS_CODE) {
            this.requestDataSources();
            this.setState({focus: false})
            await loginStore.getUserData(global.secretKey);
        }
    };

    //记录阅读次数
    _readTimes = async () => {
        const {taskStore} = this.props;
        const saveRes = await taskStore.saveTask('reading');
        // console.log('新闻详情保存任务------------>',saveRes);
    };

    renderContent = () => {
        const {dataSource} = this.state;
        return (
            <View style={styles.contentView}>
                {
                    Array.isArray(dataSource.imageVOs) ?
                        dataSource.imageVOs.map((item, i) => {
                            // console.log(`${ServicesApi.QI_NIU_LINK}${item.image_url}`);
                            if (item.image_url) {
                                return (
                                    <ImageView
                                        key={i}
                                        maxImageWidth={SCREEN_WIDTH - 30}
                                        source={{uri: `${ServicesApi.QI_NIU_LINK}${item.image_url}`}}
                                        style={[styles.contentImage, {width: SCREEN_WIDTH - 30}]}
                                    />
                                )
                            }
                        }) : null
                }
                <Text
                    style={styles.contentText}>{dataSource.information_content ? dataSource.information_content : null}</Text>
            </View>
        )
    };

    _onPressUserCenter = () => {
        RouterHelper.navigate('', 'UserCenter', {author_id: this.state.dataSource.author_id})
    };

    render() {
        const {pageTitle} = this.props.navigation.state.params;
        const {dataSource, focus} = this.state;
        let title = pageTitle || dataSource.information_title;
        return (
            <Container style={styles.container}>
                <NavigationBar
                    title={title}
                />
                <Text style={styles.title}>{dataSource.information_title}</Text>
                <View style={styles.centerInfo}>
                    <View style={styles.centerFront}>
                        <ImageView
                            style={styles.hot}
                            source={Images.icon_hot}
                        />
                        <Text
                            style={styles.number}>{dataSource.view_counts || 0}</Text>
                    </View>

                    <Text style={styles.number}>{diffTime(dataSource.publish_time ? dataSource.publish_time : 0)}</Text>
                </View>
                {dataSource.data_type === 'local' ? <View style={styles.userInfo}>
                    <View style={styles.userFront}>
                        <TouchableOpacity onPress={this._onPressUserCenter}>
                            <ImageView
                                style={styles.avatar}
                                resizeMode={'cover'}
                                source={dataSource.user_img ? {uri: dataSource.user_img} : Images.icon_default_avatar}
                            />
                        </TouchableOpacity>

                        <View>
                            <Text style={styles.userName}>{dataSource.author_name}</Text>
                            <Text
                                style={styles.fans}>粉丝：{dataSource.data_type === 'local' ? dataSource.followers_count : '未知'}</Text>
                        </View>
                    </View>
                    <TouchableOpacity style={styles.follow}
                                      onPress={focus ? this._onCancelFollow : this._onPressFollow}>
                        <Text style={styles.followText}>{focus ? '已关注' : '+ 关注'}</Text>
                    </TouchableOpacity>
                </View> : null}
                <ScrollView>
                    {dataSource.data_type === 'local' ?
                        <this.renderContent/> :
                        <HTMLView
                            imageStyle={null}
                            containerStyle={styles.htmlContainer}
                            html={`<div style="paddingLeft: 15px;paddingRight: 15px;paddingTop: 22px;color: #9d9d9d;font-size: 12px;line-height: 20px;">${dataSource.information_content}</div>`}
                            maxImageWidth={Theme.screenWidth - 20}
                        />
                    }
                </ScrollView>
                <CommentView
                    styles={styles.bottomInfo}
                    count={dataSource.topic_counts ? dataSource.topic_counts : 0}
                    topic_id={dataSource.information_id}
                    collect_state={dataSource.collect_state === '0' ? null : dataSource.collect_state}
                    reply_module={'information'}
                    title={title}
                    article_type={dataSource.article_type}
                    information={dataSource}
                    onCallBack={() => this.requestDataSources()}
                />
            </Container>
        );
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        // paddingTop: 94,
        backgroundColor: '#fff',
    },
    title: {
        fontSize: FontSize(16),
        color: '#212121',
        marginTop: 11,
        marginLeft: 15,
        marginRight: 15,
    },
    centerInfo: {
        flexDirection: 'row',
        justifyContent: 'space-between',
        marginRight: 15,
        marginLeft: 15,
        marginTop: 15,
    },
    hot: {
        width: 12,
        height: 14,
    },
    centerFront: {
        flexDirection: 'row',
    },
    number: {
        fontSize: FontSize(11),
        color: '#9d9d9d',
        marginLeft: 5,
    },
    time: {
        fontSize: FontSize(11),
        color: '#9d9d9d'
    },
    userInfo: {
        marginTop: 20,
        backgroundColor: '#f0f0f0',
        flexDirection: 'row',
        justifyContent: 'space-between',
        paddingTop: 8,
        paddingBottom: 8,
        alignItems: 'center'
    },
    userFront: {
        flexDirection: 'row',
        marginLeft: 15,
        marginRight: 15,
        alignItems: 'center'
    },
    avatar: {
        width: 41,
        height: 41,
        borderRadius: 41 / 2,
        marginRight: 10,
    },
    userName: {
        fontSize: FontSize(14),
        color: '#333'
    },
    fans: {
        fontSize: FontSize(10),
        color: '#909090',
        marginTop: 6,
    },
    follow: {
        paddingHorizontal: 10,
        paddingVertical: 5,
        borderWidth: Theme.minPixel,
        borderColor: Theme.themeColor,
        borderRadius: 10,
        marginRight: 15,
    },
    followText: {
        fontSize: FontSize(9),
        color: Theme.themeColor,
    },
    htmlContainer: {
        flex: 1,
    },
    bottomInfo: {
        flexDirection: 'row',
        position: 'absolute',
        left: 15,
        right: 15,
        bottom: 10,
        alignItems: 'center',
    },
    contentView: {
        marginVertical: 10,
        marginHorizontal: 15,
    },
    contentImage: {
        marginVertical: 15,
        alignSelf: 'center',
    },
    contentText: {
        fontFamily: "PingFangSC-Regular",
        fontSize: FontSize(14),
        color: "#9d9d9d",
        lineHeight: 20,
    },
});

export default ArticleDetails